import os
import argparse
import alibabacloud_oss_v2 as oss
from alibabacloud_credentials.client import Client as CredClient
from alibabacloud_credentials.models import Config as CredConfig


def upload_file_and_get_url(file_path,  access_key_id, access_key_secret, bucket_name, region, endpoint=None):
    """
    上传文件到阿里云OSS并返回可访问的URL

    参数:
    file_path (str): 要上传的本地文件路径
    appkey (str): 阿里云AccessKey ID
    appid (str): 阿里云AccessKey Secret
    bucket_name (str): OSS存储桶名称
    region (str): 存储桶所在区域
    endpoint (str, 可选): 自定义端点URL

    返回:
    str: 上传文件的公开访问URL
    """
    # 创建凭证配置
    # cred_config = CredConfig(
    #     access_key_id=appkey,
    #     access_key_secret=appid,
    #     type='access_key'
    # )
    # credentials = CredClient(cred_config)
    credentials_provider = oss.credentials.StaticCredentialsProvider(access_key_id, access_key_secret)
    oss_config = oss.config.load_default()
    oss_config.credentials_provider = credentials_provider

    # 配置OSS客户端
    # oss_config = oss.Config()
    # oss_config.credentials_provider = credentials
    oss_config.region = region
    if endpoint:
        oss_config.endpoint = endpoint

    # 创建OSS客户端
    client = oss.Client(oss_config)

    # 从文件路径中提取文件名
    object_name = os.path.basename(file_path)

    try:
        # 上传文件到OSS
        with open(file_path, 'rb') as file:
            put_result = client.put_object(oss.PutObjectRequest(
                bucket=bucket_name,
                key= object_name,
                body= file.read(),
            ))

        print(f'status code: {put_result.status_code},'
              f' request id: {put_result.request_id},'
              f' content md5: {put_result.content_md5},'
              f' etag: {put_result.etag},'
              f' hash crc64: {put_result.hash_crc64},'
              f' version id: {put_result.version_id},'
              )
        # 检查上传是否成功
        if put_result.status_code != 200:
            raise RuntimeError(f"文件上传失败，状态码: {put_result.status_code}")

        # 构造公开访问URL (简单版)
        if endpoint:
            base_url = f"https://{bucket_name}.{endpoint}"
        else:
            base_url = f"https://{bucket_name}.oss-{region}.aliyuncs.com"

        return f"{base_url}/{object_name}"

    except Exception as e:
        raise RuntimeError(f"OSS操作失败: {str(e)}")



if __name__ == '__main__':
    appkeyid = "LTAI5tSoNNGmbHQ3UYGQdZkU"
    appkeysecret = "6CwBBw1EqVjB6towwMcoB33k5JKrJv"
    bucket_name = "gorio"
    # region = "oss-cn-beijing"
    region = "cn-beijing"

    res =  upload_file_and_get_url("fig/wordcloud2025-07-11_13-27-07.png", appkeyid, appkeysecret,
                            bucket_name, region)
    print(res)